import React, {Component, Suspense} from 'react';
import {Row, Col, Icon, Menu, Dropdown} from 'antd';

import GridContent from '@/components/PageHeaderWrapper/GridContent';
import {getTimeDistance} from '@/utils/utils';

import styles from './Analysis.less';
import PageLoading from '@/components/PageLoading';
import {connect} from "react-redux";
import {FETCH_DATA, FETCH_RUNNING_DATA} from "../../models/dashboard/const";
import {REFRESH_DEVICES} from "../../models/device/const";
import {getDate, getDateValue} from "../../utils/utils";

import {FETCH_DEVICES} from "../../models/device/const";
import {OFFLINE, ONLINE, RUNNING} from "../../config/const";
import getDeviceList from "../../models/selectors";
import {CHANGE_QUERY_TIME} from "../../models/report/const";

//模拟的虚拟数据
import deviceLists1 from './deviceList1'
import {base_url} from '../../config/const'

import request from '@/utils/request';


const DeviceDataCard = React.lazy(() => import('./DeviceDataCard'));
const RunningDataCard = React.lazy(() => import('./RunningDataCard'));

const ALL = 3;


@connect(({loading, dashboard, device,}) => {
  return ({
    loading: loading.fetchDashboard,
    dashboardData: dashboard,
    deviceList: getDeviceList(device),//之前从
    // deviceList:deviceLists1,
  })
})

class Analysis extends Component {
    constructor(props) {
        super(props);
        this.state = {
            rangePickerValue: getTimeDistance('year'),
            device_total:0,
            test:false,
            running_device_total:0,
            online_device_total:0,
            offline_device_total:0,
            checkedKeys:{
                "-1":true,
                "0":true,
                "1":true,
                "2":true
            },
            datePickerValue: getDateValue(),
            dateType: '7days'
        };
        const {dispatch} = this.props;
        dispatch({
            type: FETCH_DEVICES,
        });

    }
    componentDidMount() {
        const {datePickerValue, dateType} = this.state;
        const values = getTimeDistance(dateType, datePickerValue);
        const start_time = parseInt(values[0].valueOf() / 1e3);
        const end_time = parseInt(values[1].valueOf() / 1e3);
        // const {dispatch} = this.props;
        // const payload = {start_time, end_time,};
        // dispatch({
        //     type: FETCH_DATA,
        //     payload,
        // });
        const {dispatch} = this.props;
        dispatch({
            type: REFRESH_DEVICES,
        });
        this.getDeviceID(['1','2','3']);
    }


    getDeviceID=async (type)=>{
        if(localStorage.getItem('user')){
            var  user=JSON.parse(localStorage.getItem('user')).username;
            var  company_id=JSON.parse(localStorage.getItem('user')).company_id;
        }
        const url=`device_list/?user=${user}&company_id=${company_id}`;
        // const url=`http://localhost:5000/api/device_list`;
        var device_total=0,offline_device_total=0,online_device_total=0,running_device_total=0;

        const response=await new Promise(resolve=>{
            request({url}).then(res=>{
                resolve(res.data);
            })
        });
        if(type&&type.length>0){
            var arr=[];
            response.data&&response.data.map(item=>{
                if(type.includes(item.type)||type.includes(parseInt(item.type))||type.includes(''+item.type)){
                    arr.push(item)
                }
            });
            arr.map(item=>{
                if(item.status==0){
                    offline_device_total++;
                }else if(item.status==1){
                    online_device_total++;
                }else if(item.status==2){
                    running_device_total++;

                }
            });
            this.setState({
                device_total:arr.length,
                test:true,
                offline_device_total,online_device_total,running_device_total
            })
        }else{
            arr=[];
            this.setState({
                device_total:0,
                test:true,
                offline_device_total:0,online_device_total:0,running_device_total:0
            })
        }

    };

    selectDate = type => {
        this.setState({
            dateType: type,
        }, () => {
            this.fetchRunningData()
        });
    };

    fetchRunningData = () => {
        const {dispatch} = this.props;
        const {datePickerValue, dateType} = this.state;
        const values = getTimeDistance(dateType, datePickerValue);
        const start_time = parseInt(values[0].valueOf() / 1e3);
        const end_time = parseInt(values[1].valueOf() / 1e3);
        dispatch({
            type: FETCH_RUNNING_DATA,
            payload: {start_time, end_time},
        });
    };

    isActive = type => {
        const {dateType} = this.state;
        if (type !== dateType) {
            return '';
        }
        if (
            type === dateType
        ) {
            return styles.currentDate;
        }
        return '';
    };

    batteryDataFormat = data => {
        if (!data) return [];
        return Object.keys(data).sort().slice(-30).map(item => ({
            x: item, y: data[item],
        }))
    };

    handleDatePickerChange = datePickerValue => {
        this.setState({
            datePickerValue,
        }, () => {
            this.fetchRunningData()
        });
    };

    handleChangeQueryTime = ()=>{
        const {dispatch, dashboardData: {end_time, start_time}} = this.props;
        dispatch({type:CHANGE_QUERY_TIME, payload:{start_time, end_time}})
    };

    render() {
        const {loading, dashboardData, deviceList, history, dispatch} = this.props;
        const {rangePickerValue, datePickerValue,checkedKeys} = this.state;
      if (!deviceList) return (<PageLoading/>);
        const {
            [OFFLINE]: offline_device_total,
            [ONLINE]: online_device_total,
            [RUNNING]: running_device_total,
            [ALL]: device_total,
        } = deviceList.reduce((obj, item) => (obj[item.status]++, obj[ALL]++, obj), {
            [OFFLINE]: 0,
            [ONLINE]: 0,
            [RUNNING]: 0,
            [ALL]: 0,
        });

        const {
            query_days,
            end_time,
            duration_total,
            stay_time,
            start_time,
            mileage_total,//总里程数
            battery_low_record,//电量低  是异常
            mileage_total_record,//总里程记录
            stay_time_record,
            duration_total_record,
            current_date,
        } = dashboardData;

        const current_running_device_total = online_device_total + running_device_total;
        const device_usage_rate = (current_running_device_total / device_total * 100).toFixed(2);
        const devicePieData1 = [
            {x: "在线设备数", y: this.state.running_device_total},
            {x: "离线设备数", y: this.state.offline_device_total},
        ];
        const devicePieData = [
            {x: "在线设备数", y: running_device_total},
            {x: "离线设备数", y: offline_device_total},
        ];
        const deviceData = {
            device_total,
            device_usage_rate,//设备使用率
        };
        const current_running_device_total1 = this.state.online_device_total + this.state.running_device_total;
        let device_usage_rate1 = (current_running_device_total1 / this.state.device_total * 100).toFixed(2)||'0';
        let deviceData1 = {
            device_total:this.state.device_total,
            device_usage_rate:device_usage_rate1,//设备使用率
        };
        const current_battery_low = (battery_low_record && battery_low_record[current_date]) || 0;
        const runningData = {
            query_days,
            current_running_device_total,
            running_device_total,
            mileage_total,
            duration_total,
            stay_time,
            mileage_total_record,
            stay_time_record,
            duration_total_record,
        };

        return (
            <GridContent>
                <Suspense fallback={<PageLoading/>}>
                    {
                        this.state.test?(<DeviceDataCard
                            datePickerValue={datePickerValue}
                            handleDatePickerChange={this.handleDatePickerChange}
                            isActive={this.isActive}
                            loading={loading}
                            getDeviceID={this.getDeviceID}
                            current_battery_low={current_battery_low}
                            devicePieData={devicePieData}
                            deviceData={deviceData}
                            batteryLowRecord={this.batteryDataFormat(battery_low_record)}
                            history={history}
                            onChangeQueryTime={this.handleChangeQueryTime}
                        />):null
                    }
                </Suspense>

                <Suspense fallback={null}>
                    <RunningDataCard
                      rangePickerValue={rangePickerValue}
                      runningData={runningData}
                      isActive={this.isActive}
                        // handleRangePickerChange={this.handleRangePickerChange}
                      loading={loading}
                      selectDate={this.selectDate}
                      history={history}
                      onChangeQueryTime={this.handleChangeQueryTime}
                    />
                </Suspense>
            </GridContent>
        );
    }
}

export default Analysis;
